extends ItemAppender


class_name ChildrenItemAppender
"""
负责给ItemContainer做适配,将元素作为指定节点的子节点使用
"""


## 挂载子节点入口
@export var container: Node = null


var item_map: Dictionary[Node, Node] = {}


static func get_or_copy(cmpt: Node) -> Node:
    return cmpt.duplicate() as Node if cmpt.get_parent() else cmpt


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "container": IComponent.find_child.bind(self, func(x): return x is Node, container)
    }, super.__check_exports())

func __init_hooks() -> Dictionary:
    return IComponent.merge({
        container.child_entered_tree: on_child_entered_tree,
        container.child_exiting_tree: on_child_exiting_tree,
    }, super.__init_hooks())

func __prepare() -> void:
    super.__prepare()
    for c in container.get_children():
        if not c is ItemAppender:
            item_container.items.append(c)

func append(node: Node) -> void:
    var copy_node: Node = ChildrenItemAppender.get_or_copy(node)
    item_map[node] = copy_node
    container.add_child(copy_node)

func remove(node: Node) -> void:
    var copy_node: Node = item_map[node]
    item_map.erase(node)
    container.remove_child(copy_node)
    copy_node.queue_free()

func on_child_entered_tree(node: Node) -> void:
    item_container.items.append(node)

func on_child_exiting_tree(node: Node) -> void:
    item_container.items.erase(node)
